﻿using System.Text;

namespace MyTRCP.Common.Models
{
    public class MyDiscoveredDevices : BitWalkableObj
    {
        public bool IsSuccess { get; set; }
        public string ExceptionMsg { get; set; } = string.Empty;
        public List<BtDevInfo> BtDevs { get; set; } = [];
        public MyDiscoveredDevices(byte[] data) : base(data) { }
        public MyDiscoveredDevices(IReadOnlyCollection<BtDevInfo>? btDevs, string? exceptionMsg)
        {
            if (btDevs != null)
            {
                IsSuccess = true;
                BtDevs = [.. btDevs];
            }
            else
            {
                IsSuccess = false;
                if (exceptionMsg != null)
                {
                    ExceptionMsg = exceptionMsg;
                }
            }
        }

        public override BitWalker ReadFromBitWalker(BitWalker bw)
        {
            IsSuccess = bw.ReadBit();
            bw.SkipBits(7);
            byte exMsgLen = (byte)bw.ReadBits(8);
            ExceptionMsg = Encoding.UTF8.GetString(bw.ReadBytes(exMsgLen));
            byte devCount = (byte)bw.ReadBits(8);
            BtDevs = [.. bw.ReadBitWalkableObjs<BtDevInfo>(devCount)];
            return bw;
        }

        public override BitWalker WriteToBitWalker(BitWalker bw)
        {
            byte[] msgBytes = Encoding.UTF8.GetBytes(ExceptionMsg);
            return bw
                .WriteBit(IsSuccess)
                .SkipBits(7)
                .WriteBits(msgBytes.Length, 8)
                .WriteBytes(msgBytes)
                .WriteBits(BtDevs.Count, 8)
                .WriteBitWalkableObjs(BtDevs);
        }
    }
}